Components.utils.import("resource://gre/modules/k9mailDb.jsm");


var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                        .getService(Components.interfaces.nsIPromptService);

/*动态设计连接引导窗口的标题*/
//var popupWindow=document.getElementById("deviceWindow");
function windowInit()
{
    
    setWindowTitle();
    createNewTabbox(window.arguments[0]);

}
function setWindowTitle()
{

    var windowManager = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator);
    var enumwindow = windowManager.getEnumerator(null);
    var win=null;
    while (enumwindow.hasMoreElements()) {
        win = enumwindow.getNext().QueryInterface(Components.interfaces.nsIDOMChromeWindow);
        if (win.name === "deviceWindowName") {
            //alert("window.arguments[0].name");
            document.title = convertToUnicode(window.arguments[0].name) + "设备连接引导";
            //alert(window.arguments[0].name);
        }
       
    }
  //window.addEventListener('resize', function(){ window.resizeTo(window.document.documentElement.minWidth,window.document.documentElement.minHeight)}, false);  
}
//window.addEventListener('resize', function(){ window.resizeTo(window.document.documentElement.minWidth,window.document.documentElement.minHeight)}, false);
//function(){setTimeout(function(){windowInit();},0);}
window.addEventListener('load', windowInit, false);
//window.addEventListener('close',linkStopDeal,false);

function linkStopDeal()
{
    var selectedDeviceStatus;
    var statement = window.arguments[1].dbConnection.createStatement("\
                  SELECT dHandleStatus FROM td_device where dUDN  = :myVal");
    statement.params.myVal = window.arguments[0].uuid;
    try {
        while (statement.executeStep()) {
            selectedDeviceStatus = statement.row.dHandleStatus;
        }
    }
    finally {
        statement.reset();
    }
    if(selectedDeviceStatus==0&&jumpflag==null)
    {
    var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);    
    var locationStr=window.arguments[0].location;    
    var httpHead = locationStr.split("/")[0];
    var ipAndPort = locationStr.split("/")[2];
    var serviceSubStr =httpHead+"\/\/"+ipAndPort+"/upnp/control/tvcontrol1";
    gEN.SendAction(serviceSubStr,"Offline","line","off");    
    }else{
        
       return; 
    }
    
}


function addOneDeviceInfo(deviceInfo, statusVal,locationVal, nameVal, udnVal) {
    deviceInfo.push({status: statusVal,location:locationVal, name: nameVal, UDN: udnVal, listID: "dev_0"});
}
/*设备离线后更新远程模块列表*/
function breakoffliveoffDevice(liveoffId){
  
            /*删除设备信息*/
            var statement = dDeviceSqlite.dbConnection.createStatement("\
                  DELETE FROM td_device where dId = :myVal");
            statement.params.myVal =liveoffId;
            try{
                 while(statement.executeStep()){
                    //statement.finalize();
                    continue;
                }
            }
            finally{
                statement.reset();
            }
            statement = dDeviceSqlite.dbConnection.createStatement("\
                  DELETE FROM td_account WHERE dId = :myVal");
            statement.params.myVal = liveoffId;
            try{
                 while(statement.executeStep()){
                    continue;
                }
            }
            finally{
                statement.reset();
            }

     var menuItem=document.getElementById("connectManagerPanel");
     var panelTree = document.getElementById("folderPaneBox");
     var elem_child = panelTree.childNodes;
     //alert(elem_child.length);
     if(elem_child.length>3){
         for(var i=0;i<elem_child.length;i++){
            if("showDevicesPanelTree"=== elem_child[i].id){
                  elem_child[i].parentNode.removeChild(elem_child[i]);         
            }
         }
         menuItem.setAttribute("checked",true);
         createOneDeviceListToPanel();
     }
}


function getOneDeviceInfos(deviceInfo)
{
    if (dDeviceSqlite.initialized && dDeviceSqlite.dbStatus) {
       
        var ListId = null;
        var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dListId FROM td_device ORDER BY dListId DESC LIMIT 0,1");
        try {
            while (statement.executeStep()) {
                ListId = statement.row.dListId;
            }
        }
        finally {
            statement.reset();
        }
        if (ListId >= 0) {
            ListId += 1;
        } else {
            ListId = 1;
        }
        for (var i = 1; i < deviceInfo.length; i++) {
            deviceInfo[i].listID = ListId++;
        }
        var statement = dDeviceSqlite.dbConnection.createStatement("\
                                   INSERT INTO td_device (dName,dLocation, dStatus, dUDN, dListId) \
                                   VALUES (:dName, :dLocation, :dStatus, :dUDN, :dListId)");
        var params = statement.newBindingParamsArray();
        for (var i = 1; i < deviceInfo.length; i++) {
            //alert("插入数据的条数="+deviceInfo.length);
            var bp = params.newBindingParams();
            bp.bindByName("dName", deviceInfo[i].name);
            bp.bindByName("dStatus", deviceInfo[i].status);
            bp.bindByName("dLocation", deviceInfo[i].location);
            bp.bindByName("dUDN", deviceInfo[i].UDN);
            bp.bindByName("dListId", deviceInfo[i].listID);
            params.addParams(bp);
        }
        statement.bindParameters(params);
        statement.executeAsync({handleCompletion: function (aReason) {
                while (1) {
                    if (aReason !== Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) {
                        continue;
                    } else {
                        break;
                    }
                }
            }});
        statement.finalize();
//        dDeviceSqlite.onClose();
    } else {
        dDeviceSqlite.onLoad();
        getOneDeviceInfos();
    }
    return true;
}


function createNewTabbox(selectedDeviceInfo) {
    var deviceTabs = document.getElementById("erweima");

    deviceTabs.setAttribute("minheight", "380");
    deviceTabs.setAttribute("maxheight", "380");
 
    var curUDN = selectedDeviceInfo.uuid;

    var tarCode = curUDN.substr(curUDN.length - 6, curUDN.length);
 
 
    setTimeout("checkAlidyResult()",100);
    generationDEVQRCode(deviceTabs.id, tarCode);//tarCode
   
   
    
}
var jumpflag=null;
function checkAlidyResult()
{
    var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
    //gEN = gEN.QueryInterface(Components.interfaces.nsIUpnpService);
    //alert("asaaa"+gEN.flag);
    var flagnow=gEN.flag;
   
    if(flagnow=="success")//
    {
         //alert(flagnow);
        gEN.flag="aas";
        clearTimeout(timeSwitch);
        jumpflag="success";
        devLinkSuccess();
        
    }else if(flagnow=="timeout")
    {
         //alert(flagnow);
        gEN.flag="aas";
        //clearTimeout(timeSwitch);
        jumpflag="fail";
        linkerrorjump();
         //alert("222222");
        
    }
    else
    { 
        //alert("阻碍");
        timeSwitch=setTimeout("checkAlidyResult()",100);
    }    
}

function getOneDevAccountsInfo() {
    var accountsInfo = [{aName: "账户名", aPwd: "用户密码", aXml:"数据XML文件",aServiceType: "服务类型", dId: 0}];
    var accountList=window.arguments[0].get();
    //alert("accountList.length"+accountList)
     if(accountList !== null)
       {
               var auuid = Components.ID("{f5e32d2b-646a-4f2c-b011-d343dbc3bc60}");
               var al = accountList.length;
               //("sadadfsdf"+al);
               for(var j = 0;j < accountList.length;j++)
               {
                   //alert(i);
                   var Account = accountList.queryElementAt(j,auuid);
                   let ANameS = Account.name;
                   let APwdS  = Account.password;
                   let AServiceS = Account.service;
                   let AXmlS=Account.accountid;
              
                   //alert(ANameS);
                   accountsInfo.push({aName: ANameS, aPwd: APwdS, aXml: AXmlS, aServiceType: AServiceS, dId: 0});
                   //alert("account name");
                   
                }
               accountList.length=0;       
        }
    
    //accountsInfo.push({aName: "zelei@nfs-hlj.com", aPwd: escape("密码测试"), aServiceType: "imap", dId: 0});
    //accountsInfo.push({aName: "525898211@qq.com", aPwd: escape("密码测试"), aServiceType: "pop3", dId: 0});
    //alert("asldfalf");
    return accountsInfo;
}

/*test link state*/
function testgetAccountsInfo() {

var accountsInfo = [{aName: "账户名", aPwd: "用户密码", aXml:"数据XML文件",aServiceType: "服务类型", dId: 0}];
    accountsInfo.push({aName: "zelei@nfs-hlj.com", aPwd: escape("密码测试"),aXml: "3da2027a-6ec2-4b81-a8c5-ad811a5763a6_message.xml", aServiceType: "imap", dId: 0});
    accountsInfo.push({aName: "525898211@qq.com", aPwd: escape("密码测试"),aXml: "3da2027a-6ec2-4b81-a8c5-ad811a5763a6_message.xml",aServiceType: "pop3", dId: 0});
    //alert("asldfalf");
return accountsInfo;

}

var selectedDeviceID;
function saveDevAccountsInfoToDB(tabpanelID) {
    
    var accounstInfo = getOneDevAccountsInfo();
    
    //var accounstInfo =testgetAccountsInfo();
    var selectedTabPanelID = tabpanelID;
    //var selectedDeviceListID = selectedTabPanelID.split("_")[2];
    var statement = window.arguments[1].dbConnection.createStatement("\
                  SELECT dId FROM td_device where dUDN  = :myVal");
    statement.params.myVal = window.arguments[0].uuid;
    try {
        while (statement.executeStep()) {
            selectedDeviceID = statement.row.dId;
        }
    }
    finally {
        statement.reset();
    }
    statement = window.arguments[1].dbConnection.createStatement("INSERT INTO \
                           td_account (aName, aPwd, aXml,dId, aServiceType) \
                           VALUES (:aName, :aPwd, :aXml,:dId, :aServiceType)");
    var params = statement.newBindingParamsArray();
    for (var i = 1; i < accounstInfo.length; i++) {
        var bp = params.newBindingParams();
        bp.bindByName("dId", selectedDeviceID);
        bp.bindByName("aPwd", accounstInfo[i].aPwd);
        bp.bindByName("aName", accounstInfo[i].aName);
        bp.bindByName("aXml", accounstInfo[i].aXml);
        bp.bindByName("aServiceType", accounstInfo[i].aServiceType);
        params.addParams(bp);
    }
    statement.bindParameters(params);
    statement.executeAsync({handleCompletion: function (aReason) {
            while (1) {
                if (aReason !== Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) {
                    continue;
                } else {
                    break;
                }
            }
        }});
    statement.finalize();
    accounstInfo.length=0;
}


function createAccInfoPanel(panelID) {
    var index = panelID;
    //alert("index="+index);
    var curTabpanel = document.getElementById(panelID);

    var mainBox = document.createElement("vbox");
    mainBox.setAttribute("id", "tabpanel_vbox_" + index);
    mainBox.setAttribute("flex", "1");
    //mainBox.setAttribute("minwidth", "360");
    //mainBox.setAttribute("height", "240");
    //mainBox.setAttribute("flex", "1");
    //mainBox.setAttribute("flex", "1");
    //mainBox.setAttribute("orient","vertical");
    //mainBox.setAttribute("style","overflow:auto");
//mainBox.setAttribute("style","margin-left:30px;");
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style", "height:15px");
    mainBox.appendChild(tmpSpacer);
    var headerBox = document.createElement("hbox");
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style", "width:25px");
    headerBox.appendChild(tmpSpacer);
    var strLabel = document.createElement("label");
    strLabel.setAttribute("value", "当前设备内邮箱账户");
    headerBox.appendChild(strLabel);
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style", "width:100px");
    headerBox.appendChild(tmpSpacer);
    var strLabel = document.createElement("label");
    strLabel.setAttribute("value", "服务类型");
    headerBox.appendChild(strLabel);
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style", "width:200px");
    headerBox.appendChild(tmpSpacer);
    var strLabel = document.createElement("label");
    strLabel.setAttribute("value","管理模式");
    headerBox.appendChild(strLabel);
    mainBox.appendChild(headerBox);
    var mainGroupBox = document.createElement("groupbox");
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style", "height:15px");
    mainGroupBox.appendChild(tmpSpacer);
    var mainGrid = document.createElement("grid");
    mainGrid.setAttribute("maxheight","220px");
    mainGrid.setAttribute("minheight","220px");
    mainGrid.setAttribute("style","overflow:auto");
    var columnheader = document.createElement("columns");
    var column = document.createElement("column");
    column.setAttribute("flex", "3");
    columnheader.appendChild(column);
    var column = document.createElement("column");
    column.setAttribute("flex", "1");
    columnheader.appendChild(column);
    var column = document.createElement("column");
    column.setAttribute("flex", "1");
    columnheader.appendChild(column);
    var column = document.createElement("column");
    column.setAttribute("flex", "1");
    columnheader.appendChild(column);
    mainGrid.appendChild(columnheader);
    var rowheader = document.createElement("rows");
    
      //alert(23333);
      var accountsInfo = [{aName: "账户名",
            aServiceType: "服务类型",
            aLocalStatus: "本地状态",
            aRemoteStatus: "远程状态",
            aLastStatus: "最后状态",
            dId: 0,
            aId: 0}];
    var statement = window.arguments[1].dbConnection.createStatement("\
                  SELECT * FROM td_account where did = :myVal");
    statement.params.myVal = selectedDeviceID;
    //alert(24444);
    try {
        while (statement.executeStep()) {
            accountsInfo.push({
                aName: statement.row.aName,
                aServiceType: statement.row.aServiceType,
                aLocalStatus: statement.row.aLocalStatus,
                aRemoteStatus: statement.row.aRemoteStatus,
                aLastStatus: statement.row.aLastStatus,
                dId: statement.row.dId,
                aId: statement.row.aId});
        }
    }
    finally {
        statement.reset();
    }
        //alert(25555);
    for (var i = 1; i < accountsInfo.length; i++) {
        var newRow = document.createElement("row");
        newRow.setAttribute("id", "tab_panel_row_" + index + "_" + accountsInfo[i].dId);
        var checkbox = document.createElement("checkbox");
        checkbox.setAttribute("id", "tab_panel_row_checkbox_" + index + "_" + accountsInfo[i].aId);
        var strName = (accountsInfo[i].aName).split("@")[0];
        var strTempName = null;
        if (strName.length > 5) {
            var tempStr = strName.substr(0, 5);
            strTempName = tempStr + "****@" + (accountsInfo[i].aName).split("@")[1];
        } else {
            strTempName = strName + "****@" + (accountsInfo[i].aName).split("@")[1];
        }
        checkbox.setAttribute("label", strTempName);
        newRow.appendChild(checkbox);
        var tmpSpacer = document.createElement("spacer");
        tmpSpacer.setAttribute("style", "width:15px");
        newRow.appendChild(tmpSpacer);
        var listbox = document.createElement("listbox");
        listbox.setAttribute("id", "tab_panel_row_listbox_" + index + "_" + accountsInfo[i].aId);
        listbox.setAttribute("style", "width:70px");
        listbox.setAttribute("seltype", "cell");
        listbox.setAttribute("rows", "1");
        var listItem_pop3 = document.createElement("listitem");
        listItem_pop3.setAttribute("id", "tab_panel_row_listbox_listitempop3_" + index + "_" + accountsInfo[i].aId);
        listItem_pop3.setAttribute("value", "pop3");
        listItem_pop3.setAttribute("label", "POP3");
        var listItem_imap = document.createElement("listitem");
        listItem_imap.setAttribute("id", "tab_panel_row_listbox_listitemimap_" + index + "_" + accountsInfo[i].aId);
        listItem_imap.setAttribute("value", "imap");
        listItem_imap.setAttribute("label", "IMAP");
        if ('pop3' === accountsInfo[i].aServiceType) {
            listItem_pop3.setAttribute("selected", "true");
        } else {
            listItem_imap.setAttribute("selected", "true");
        }
        listbox.appendChild(listItem_pop3);
        listbox.appendChild(listItem_imap);
        newRow.appendChild(listbox);
        var tmpSpacer = document.createElement("spacer");
        tmpSpacer.setAttribute("style", "width:160px");
        newRow.appendChild(tmpSpacer);
        var menulist = document.createElement("menulist");
        menulist.setAttribute("id", "tab_panel_row_menulist_" + index + "_" + accountsInfo[i].aId);
        var menupopup = document.createElement("menupopup");
        menupopup.setAttribute("id", "tab_panel_row_menulist_menupopup_" + index + "_" + accountsInfo[i].aId);
        menulist.appendChild(menupopup);
        var menuitem_remote = document.createElement("menuitem");
        var menuitem_local = document.createElement("menuitem");
        var menuitem_none = document.createElement("menuitem");
        var menuitem_close = document.createElement("menuitem");
        if (1 === accountsInfo[i].aLastStatus) {
            menuitem_local.setAttribute("selected", "true");
        } else if (2 === accountsInfo[i].aLastStatus) {
            menuitem_remote.setAttribute("selected", "true");
        } else if (0 === accountsInfo[i].aLastStatus) {
            menuitem_none.setAttribute("selected", "true");
        } else if (3 === accountsInfo[i].aLastStatus) {
            menuitem_close.setAttribute("selected", "true");
        } else {
            prompts.alert(null, "提示", "数据库中账户管理类型异常错误...");
            //alert("数据库中账户管理类型异常错误...");
            return;
        }
        menuitem_none.setAttribute("label", "选择模式");
        menupopup.appendChild(menuitem_none);
        menuitem_local.setAttribute("label", "本地管理");
        menupopup.appendChild(menuitem_local);
        menuitem_remote.setAttribute("label", "远程管理");
        menupopup.appendChild(menuitem_remote);
        menuitem_close.setAttribute("label", "注销管理");
        menupopup.appendChild(menuitem_close);
        newRow.appendChild(menulist);
        var tmpSpacer = document.createElement("spacer");
        tmpSpacer.setAttribute("style", "width:70px");
        newRow.appendChild(tmpSpacer);
        rowheader.appendChild(newRow);
    }
  
    mainGrid.appendChild(rowheader);
    mainGroupBox.appendChild(mainGrid);
    mainBox.appendChild(mainGroupBox);
 
    var tmpSpacer = document.createElement("spacer");
    tmpSpacer.setAttribute("style", "height:15px");
    mainBox.appendChild(tmpSpacer);
    var mainHbox = document.createElement("hbox");
    mainHbox.setAttribute("align", "right");
    mainHbox.setAttribute("style", "margin-right:68px;");
    var btnCreate = document.createElement("button");
    btnCreate.setAttribute("id", "tab_panel_row_box_button_create_" + index);
    btnCreate.setAttribute("label", "提交");
    //alert("processCreateAccountRequest1213");
    btnCreate.setAttribute("oncommand", "processCreateAccountRequest();");
    //alert("processCreateAccountRequest");
    mainHbox.appendChild(tmpSpacer);
    mainHbox.appendChild(btnCreate);
   
    //alert(1232523);
    mainBox.appendChild(tmpSpacer);
    mainBox.appendChild(mainHbox);
    mainBox.appendChild(tmpSpacer);
    //alert(232424);
    curTabpanel.appendChild(mainBox);
    //alert("sadfaldf");
}

function processCreateAccountRequest() {
    //var selectedTabPanelID = event.target.parentNode.id;
    
    var deviceTabs = document.getElementById("messagepaneboxwrapper");
    var index = deviceTabs.id;
    //alert(index);
    //alert(index);
    var devstatement = window.arguments[1].dbConnection.createStatement("\
                  SELECT dId FROM td_device where dUDN = :myVal");
     devstatement.params.myVal = window.arguments[0].uuid;
    
    var statement = window.arguments[1].dbConnection.createStatement("\
                  SELECT aId FROM td_account where dId = :myVal");
    try {
        while (devstatement.executeStep()) {
               statement.params.myVal = devstatement.row.dId;
        }
    }
    finally {
        devstatement.reset();
    }
 
    var checkBoxIndexArray = new Array();
    try {
        while (statement.executeStep()) {
            checkBoxIndexArray.push(statement.row.aId);
        }
    }
    finally {
        statement.reset();
    }
    var ckeckboxItem = new Array();
    var selectedCheckbox = new Array();
    //alert("checkBoxIndexArray.length ="+checkBoxIndexArray.length);
    for (var i = 0; i < checkBoxIndexArray.length; i++) {
        //var testid=document.getElementById("tab_panel_row_checkbox_" + index + "_" + checkBoxIndexArray[i]);
        //alert(testid.id);
        ckeckboxItem.push(document.getElementById("tab_panel_row_checkbox_" + index + "_" + checkBoxIndexArray[i]));
    }
    if (ckeckboxItem.length) {
        var isCheckboxChecked = false;
        for (var i = 0; i < ckeckboxItem.length; i++) {
            if (ckeckboxItem[i].checked) {
                isCheckboxChecked = true;
                //alert(ckeckboxItem[i].id);
                selectedCheckbox.push(ckeckboxItem[i]);
            }
        }
        if (isCheckboxChecked) {
            try{ 
                 //alert("获取通讯录信息");
                 sentgetContactsAction(selectedCheckbox[0].id);
            for (var i = 0; i < selectedCheckbox.length; i++) {
                //alert("selectedCheckbox.length="+selectedCheckbox.length);
                if (executeSelectOpr(selectedCheckbox[i].id)) {
                    continue;
                } else {
                    break;
                }
                //window.close();
            }
        }catch(e){            
            for (var i = 0; i < selectedCheckbox.length; i++) {
                //alert("selectedCheckbox.length="+selectedCheckbox.length);
                if (executeSelectOpr(selectedCheckbox[i].id)) {
                    continue;
                } else {
                    break;
                }
            }            
        }
                               
        } else {
             prompts.alert(null, "提示", "请选择需要创建的一个或几个账户...");
            //alert("请选择需要创建的一个或几个账户...");
            return;
        }
    } else {
         prompts.alert(null, "提示", "请选择需要创建的一个或几个账户...");
        //alert("请选择需要创建的一个或几个账户...");
        return;
    }
    //window.close();
}

/*远程模式点击提交实现获取账户内邮件头信息*/
function sentgetMsgHeadAction(id,managerMode)
{
    
    var locationStr=null;
    var xmlFile=null;
    var dIdNum=null;
      var devName=null;
    var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
    var statement = window.arguments[1].dbConnection.createStatement("\
                  SELECT aXml,dId FROM td_account where aId = :myVal");
                  statement.params.myVal = id;
                 
        try {
                 while (statement.executeStep()) {
                      xmlFile = statement.row.aXml;
                      dIdNum = statement.row.dId;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
    var statement = window.arguments[1].dbConnection.createStatement("\
                  SELECT dLocation,dName FROM td_device where dId = :myVal");
                  statement.params.myVal = dIdNum;
                 
        try {
                 while (statement.executeStep()) {
                      locationStr = statement.row.dLocation;
                      devName =statement.row.dName;
                      }
                   }
                 
        finally {
                  statement.reset();
                }            
      
    var httpHead = locationStr.split("/")[0];
    var ipAndPort = locationStr.split("/")[2];
    var serviceSubStr=httpHead+"\/\/"+ipAndPort+"/upnp/control/tvcontrol1";
    //alert(serviceSubStr);
    
   //alert(xmlFile);
   //GetAppMail,AccName,MessageId;        
    if(managerMode==="Remote")
    {     
      
      //gEN.mpath=lpath;
      gEN.SendAction(serviceSubStr,"GetAllEmail",xmlFile,managerMode);
      //gEN.downfile(serviceSubStr,"contacts.xml");
      //parserLocalFile("3da2027a-6ec2-4b81-a8c5-ad811a5763a6_message.xml",devName);
//      setTimeout(function(){
//        var dn=devName;
//        var fn=xmlFile;        
//        checkDownLoadResult(fn,dn);
//       },1000); 
    }
    else if(managerMode==="Destory")
    {
       /*删除该账户内的邮件头信息*/
//        var statement = dDeviceSqlite.dbConnection.createStatement("\
//                  DELETE FROM td_email WHERE eName = :myVal and dId =:myVal1");
//                  statement.params.myVal = xmlFile.split("_")[0];
//                  statement.params.myVal1 = dIdNum;
//            try{
//                 statement.executeStep();
//            }
//            finally{
//                statement.reset();
//            }
    gEN.SendAction(serviceSubStr,"GetAllEmail",xmlFile,managerMode); 
    Components.utils.import("resource://gre/modules/FileUtils.jsm");
    //Components.utils.import("resource://gre/modules/NetUtil.jsm");     
    var filetmp = FileUtils.getFile("ProfD", [xmlFile]);
    if(filetmp.exists())
    {
        filetmp.remove(true);
    }else{
        return;
    }
    }
   
}

function checkDownLoadResult(fileName,devName)
{
     //var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
  
    //var flagnow=gEN.actionValue;
      //alert("flagnow="+flagnow);
    //alert(2323);
    //alert(fileName);
    Components.utils.import("resource://gre/modules/FileUtils.jsm");  
    var filetmp = FileUtils.getFile("TmpD",[fileName]);
    //alert(fileName);
    var eflag = filetmp.exists();
    var iflag = filetmp.isReadable();
    //alert(eflag);
    //var flag=false;
    //&&iflag
   // alert("定时开关");
    if(eflag&&iflag)
    {
         //alert("定时开关");
         var t = 10000000;
         while(t > 0)
         {
             t --;
         }
         clearTimeout(timeSwitch);
         parserLocalFile(fileName,devName);
         //break;
        //gEN.actionValue="error";
    }
    else
    { 
        var timeSwitch=setTimeout(function () {
        var dn=devName;
        var fn=fileName; 
        checkDownLoadResult(fn,dn);
    },1000);
    }   
}
/*获取远程连接设备中的通讯录信息*/
function sentgetContactsAction(deviceid)
{
    
   var locationStr=null;
    var xmlFile=null;
    var dIdNum=null;
    var linkdevName=null;
    var id = deviceid.split("_")[5];
    var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dId FROM td_account where aId = :myVal");
                  statement.params.myVal = id;
                 
        try {
                 while (statement.executeStep()) {
                      //xmlFile = statement.row.aXml;
                      dIdNum = statement.row.dId;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dLocation,dName FROM td_device where dId = :myVal");
                  statement.params.myVal = dIdNum;
                  
        try {
                 while (statement.executeStep()) {
                      locationStr = statement.row.dLocation;
                      linkdevName=statement.row.dName;
                      }
                   }
                 
        finally {
                  statement.reset();
                }            
      
    var httpHead = locationStr.split("/")[0];
    var ipAndPort = locationStr.split("/")[2];
    var serviceSubStr=httpHead+"\/\/"+ipAndPort+"/contacts/contacts.xml";
    //alert(serviceSubStr);
     var dirService = Components.classes["@mozilla.org/file/directory_service;1"].
    getService(Components.interfaces.nsIProperties);
    var dir = dirService.get("ProfD", Components.interfaces.nsIFile);
    var pathS = dir.path;
    var pathc="../../../.."+pathS;
    //var pathc=gEN.path;
    var lpath=pathc+"/contacts.xml";
    //alert(lpath);
    gEN.downfile(serviceSubStr,lpath);
    ////GetAppMail,AccName,MessageId;
    //alert(1);
    Components.utils.import("resource://gre/modules/FileUtils.jsm");  
    var filetmp = FileUtils.getFile("ProfD",["contacts.xml"]);
    var eflag = filetmp.exists();
    if(eflag)
    {    
      var t = 1000000;
      while(t > 0)
      {
        t--;
      }  
      parserLocalFile("contacts.xml",linkdevName);
    }  
    //parserLocalFile("contacts.xml",linkdevName); 
    //alert("ret="+ret);
//     setTimeout(function () {
//        var dn=linkdevName;
//        var fn="contacts.xml";        
//        checkDownLoadResult(fn,dn);
//    },1000);
  
//    var genflag=gEN.actionValue;
//    if(genflag==='success')
//    {
//       gEN.actionValue="error"; 
//       alert("文件名："+xmlFile); 
//       parserLocalFile(xmlFile);//获取指定账户内的邮件头信息，完成XML数据解析，数据库信息的插入；
//       alert("加载邮件头信息成功！");       
//    }else{
//        
//       alert("加载邮件头信息失败！");
//    }
}



function executeSelectOpr(elem_item_id) {
    var curDeviceListIndex = elem_item_id.split("_")[4];
    //alert("curDeviceListIndex="+curDeviceListIndex);
    var curAccountListIndex = elem_item_id.split("_")[5];
    //alert("curAccountListIndex="+curAccountListIndex);
    //alert("zhixingwo");
    var serviceTypeItem = document.getElementById("tab_panel_row_listbox_" + curDeviceListIndex + "_" + curAccountListIndex);
    var serviceType = serviceTypeItem.selectedItem;
    //alert("leetest="+serviceType.value);
    var curSelmenuListID = "tab_panel_row_menulist_" + curDeviceListIndex + "_" + curAccountListIndex;
    var curListItem = document.getElementById(curSelmenuListID);
    var curSelListItemIndex = curListItem.selectedIndex;
    //alert("curSelListItemIndex="+curSelListItemIndex);
    switch (curSelListItemIndex) {
        case 0:
        {
            prompts.alert(null, "提示", "请确定远程/本地管理行为...");//alert("请确定远程/本地管理行为...");
            return false;
        }
        case 1:
        {
            //alert("我是本地");
            createEAccountToLocal(curAccountListIndex, serviceType.value, 1);
            //sentgetMsgHeadAction(curAccountListIndex,"Local");
            break;
        }
        case 2:
        {
            //alert("我是远程");
            createEAccountToRemote(curAccountListIndex, serviceType.value, 2);
            sentgetMsgHeadAction(curAccountListIndex,"Remote");
            break;
        }
        case 3:
        {
            closeAccountSyncPattern(curAccountListIndex, 0);
            sentgetMsgHeadAction(curAccountListIndex,"Destroy");
            break;
        }
        default:
            break;
    }
    return true;
}

function createEAccountToLocal(accountID, sStatus, aControlType) {
    //alert('jinhai');
    var statement = window.arguments[1].dbConnection.createStatement("UPDATE td_account \
                           SET aLocalStatus = :myStatus, aLastStatus = :myStatus,\
                           aControlType = 1,aServiceType = :myServiceType where aId = :myID");
    statement.params.myID = accountID;
    statement.params.myStatus = aControlType;
    statement.params.myServiceType = sStatus;
    try {
        while (statement.executeStep()) {
            continue;
        }
    }
    finally {
        statement.reset();
    }
      //alert('jinhai1');
    statement = window.arguments[1].dbConnection.createStatement("SELECT aName, aPwd ,aServiceType FROM td_account WHERE aId = :myID");
    statement.params.myID = accountID;
    try {
        while (statement.executeStep()) {
            gLocalAccountInfo.emailAddress = statement.row.aName;
            gLocalAccountInfo.userName = (statement.row.aName).split("@")[0];
            gLocalAccountInfo.passWord = statement.row.aPwd;
            gLocalAccountInfo.recvHostname="pop."+(statement.row.aName).split("@")[1];
            gLocalAccountInfo.sendHostname="smtp."+(statement.row.aName).split("@")[1];
            if((statement.row.aName).split("@")[1]=="163.com")
            {
                gLocalAccountInfo.recvPort="110";
                gLocalAccountInfo.socketType='3';
                
            }else if((statement.row.aName).split("@")[1]=="126.com"){
                
                gLocalAccountInfo.recvPort="110";
                gLocalAccountInfo.socketType='3';
                
            }else if((statement.row.aName).split("@")[1]=="qq.com")
            {
                gLocalAccountInfo.recvPort="995";
                gLocalAccountInfo.socketType='2';
                gLocalAccountInfo.sendPort='465';
                
            }else if((statement.row.aName).split("@")[1]=="sina.com"){
                
                gLocalAccountInfo.recvPort="110";
                gLocalAccountInfo.socketType='1';
                gLocalAccountInfo.sendPort='587';
                 
            }else if((statement.row.aName).split("@")[1]=="gmail.com"){
                gLocalAccountInfo.recvPort="995";
                gLocalAccountInfo.socketType='2';
                gLocalAccountInfo.sendPort='465';
            }else if((statement.row.aName).split("@")[1]=="nfs-hlj.com")
            {
                gLocalAccountInfo.recvPort="995";
                gLocalAccountInfo.socketType='2';
                gLocalAccountInfo.sendPort='465';
                gLocalAccountInfo.recvHostname="pop3.nfschina.com";
                gLocalAccountInfo.sendHostname="smtp.nfschina.com";
            }else{
                gLocalAccountInfo.recvPort="995";
                gLocalAccountInfo.socketType='2';
                gLocalAccountInfo.sendPort='465';
            }
        }
    }
    finally {
        statement.reset();
    }
    var config = new AccountConfig();
    checkIncomingServerAlreadyExists(config);
    config.rememberPassword = true;
    createAccountInBackend(config);
}

function createEAccountToRemote(accountID, sStatus, ControlType) {
    var statement = window.arguments[1].dbConnection.createStatement("UPDATE td_account \
                          SET aRemoteStatus = :myStatus, aLastStatus = :myStatus,\
                          aControlType = 1,aServiceType = :myServiceType where aId = :myID");
    statement.params.myID = accountID;
    statement.params.myStatus = ControlType;
    statement.params.myServiceType = sStatus;
    try {
        while (statement.executeStep()) {
            continue;
        }
    }
    finally {
        statement.reset();
    }
    //var folderPane =  document.getElementById('folderPaneBox');
    //var selectMenuItem = document.getElementById("connectManagerPanel");
    var menuItem = window.opener.document.getElementById("connectManagerPanel");
            //arguments[1];
    menuItem.setAttribute("checked", true);

    var panelTree = window.opener.document.getElementById('folderPaneBox');
            //arguments[0];
    //alert("panelTree="+panelTree);
    //alert("menuItem="+menuItem);
    var elem_child = panelTree.childNodes;
    for (var i = 0; i < elem_child.length; i++) {
        if ("showDevicesPanelTree" === elem_child[i].id) {
            elem_child[i].parentNode.removeChild(elem_child[i]);
        }
    }
    createOneDeviceListToPanel();
}

function closeAccountSyncPattern(accountID, aControlType) {
    //alert("accountID="+accountID);
    var panelTree=null;
    var statement = window.arguments[1].dbConnection.createStatement("\
                     UPDATE td_account SET aRemoteStatus = :myStatus, aLastStatus = 3,\
                     aControlType = 0 where aId = :myID");
    statement.params.myID = accountID;
    statement.params.myStatus = aControlType;
    try {
        while (statement.executeStep()) {
            continue;
        }
    }
    finally {
        statement.reset();
    }
    //alert(123444);
    if(window.opener)
    {
        //alert("me"+window.arguments[0]);
        panelTree = window.opener.document.getElementById("folderPaneBox");
    
    }else{
        
        panelTree = document.getElementById('folderPaneBox');
      
    }
    var elem_child = panelTree.childNodes;
    for (var i = 0; i < elem_child.length; i++) {
        if ("showDevicesPanelTree" === elem_child[i].id) {
            elem_child[i].parentNode.removeChild(elem_child[i]);
        }
    }
    //alert(panelTree);
    createOneDeviceListToPanel();
}

function createOneDevicePanel() {
    if(window.opener)
    {    
      var panelTree = window.opener.document.getElementById('folderPaneBox');
      var treeSpr= window.opener.document.getElementById('hadTreeOrNewTree');
    }else{
      var panelTree = document.getElementById('folderPaneBox');
      var treeSpr= document.getElementById('hadTreeOrNewTree');
    }
    
    //var treeSpr= window.opener.document.getElementById('hadTreeOrNewTree');
    if(!treeSpr)
    {    
      var treeSplitter = document.createElement("splitter");
          treeSplitter.setAttribute("id", "hadTreeOrNewTree");
          treeSplitter.setAttribute("collapse", "before");
          panelTree.appendChild(treeSplitter);
      
    }      
    var newTreePanel = document.createElement("tree");
    newTreePanel.setAttribute("id", "showDevicesPanelTree");
    newTreePanel.setAttribute("class", "plain");
    newTreePanel.setAttribute("flex", "1");
    newTreePanel.setAttribute("hidecolumnpicker", "true");
    newTreePanel.setAttribute("persist", "mode");
    newTreePanel.setAttribute("mode", "all");
    newTreePanel.setAttribute("keepcurrentinview", "true");
    newTreePanel.setAttribute("context", "mobileDevicePaneContext");
    newTreePanel.setAttribute("disableKeyNavigation", "true");
    newTreePanel.setAttribute("onselect", "DevicePaneSelectionHandle();");//DevicePaneSelectionHandle();
    if (panelTree) {
        var newTreeCols = document.createElement("treecols");
        newTreeCols.setAttribute("id", "firsttreecols");
        if (newTreeCols) {
            var newTreecol = document.createElement("treecol");
            newTreecol.setAttribute("id", "firstcol");
            newTreecol.setAttribute("flex", "5");
            newTreecol.setAttribute("crop", "center");
            newTreecol.setAttribute("persist", "width");
            newTreecol.setAttribute("hideheader", "true");
            newTreecol.setAttribute("ignoreincolumnpicker", "true");
            newTreecol.setAttribute("primary", "true");
            newTreecol.setAttribute("sortActive", "true");
            newTreecol.setAttribute("sortDirection", "ascending");
            newTreeCols.appendChild(newTreecol);
        }
        newTreePanel.appendChild(newTreeCols);
    }
    panelTree.appendChild(newTreePanel);

    var newTreechildren = document.createElement("treechildren");
    if (newTreechildren) {
        var newTreeitem = document.createElement("treeitem");
        newTreeitem.setAttribute("container", "true");
        newTreeitem.setAttribute("open", "true");
        if (newTreeitem) {
            var newTreerow = document.createElement("treerow");
            var newTreecell = document.createElement("treecell");
            newTreecell.setAttribute("label", "终端邮件");
            newTreerow.appendChild(newTreecell);
            newTreeitem.appendChild(newTreerow);
        }
        newTreechildren.appendChild(newTreeitem);
    }
    newTreePanel.appendChild(newTreechildren);
    return newTreeitem;
}
/*更改终端显示树的设备ID 及账户ID的方法*/

function getNewDevicesInfo(){
    
    var comingDevices = new Array();
     if(window.arguments[1])
    {     
    while(window.arguments[1].initialized ===false || window.arguments[1].dbStatus===false){
        window.arguments[1].onLoad(); 
    }
    var statement = window.arguments[1].dbConnection.createStatement("\
              SELECT dId,dName FROM td_device WHERE dStatus = 2 ORDER BY dId ASC");
    try{
        while(statement.executeStep()){
            comingDevices.push({dId:statement.row.dId,
                    dName:statement.row.dName}); 
        }
    }
    finally{
        statement.reset();
    }
    }else{
       while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
              SELECT dId,dName FROM td_device WHERE dStatus = 2 ORDER BY dId ASC");
    try{
        while(statement.executeStep()){
            comingDevices.push({dId:statement.row.dId,
                    dName:statement.row.dName}); 
        }
    }
    finally{
        statement.reset();
    }   
    }
    return comingDevices;
}

function getNewDeviceAccounts(){
    var devicesCount = new Array();
  if(window.arguments[1])
  {
    while(window.arguments[1].initialized ===false || window.arguments[1].dbStatus===false){
        window.arguments[1].onLoad(); 
    }
  
    var statement = window.arguments[1].dbConnection.createStatement("\
                            SELECT dId FROM td_device WHERE dStatus = 2");
    try{
        while(statement.executeStep()){
            devicesCount.push(statement.row.dId); 
        }
    }
    finally{
        statement.reset();
    }
 
    var comingDeviceAccounts = new Array();
    for(i=0;i<devicesCount.length;i++){
        comingDeviceAccounts[i] = new Array();
    }
    
    while(window.arguments[1].initialized ===false || window.arguments[1].dbStatus===false){
        window.arguments[1].onLoad(); 
    }
    var statement = window.arguments[1].dbConnection.createStatement("\
                SELECT td_device.dId,td_account.aId,td_account.aName FROM td_account \
                    LEFT JOIN td_device ON td_device.dId = td_account.dId \
                   WHERE td_account.aRemoteStatus = 2 ORDER BY td_device.dId ASC"); 
    try{
        var index = 0, tmp = 0;
        while(statement.executeStep()){
            if(0 == tmp){
                tmp = statement.row.dId;
                  comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
            }else{
                if(tmp === statement.row.dId){
                    comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
                }else{
                    tmp = statement.row.dId;
                    index++;
                    comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
                }
            }
        }
    }
    finally{
        statement.reset();
    }
  }else{     
         while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                            SELECT dId FROM td_device WHERE dStatus = 2");
    try{
        while(statement.executeStep()){
            devicesCount.push(statement.row.dId); 
        }
    }
    finally{
        statement.reset();
    }
 
    var comingDeviceAccounts = new Array();
    for(i=0;i<devicesCount.length;i++){
        comingDeviceAccounts[i] = new Array();
    }
    
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                SELECT td_device.dId,td_account.aId,td_account.aName FROM td_account \
                    LEFT JOIN td_device ON td_device.dId = td_account.dId \
                   WHERE td_account.aRemoteStatus = 2 ORDER BY td_device.dId ASC"); 
    try{
        var index = 0, tmp = 0;
        while(statement.executeStep()){
            if(0 == tmp){
                tmp = statement.row.dId;
                  comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
            }else{
                if(tmp === statement.row.dId){
                    comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
                }else{
                    tmp = statement.row.dId;
                    index++;
                    comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
                }
            }
        }
    }
    finally{
        statement.reset();
    }        
  }
    return comingDeviceAccounts;
}



function createOneDeviceListToPanel() {
    var Treeitem = createOneDevicePanel();

    var newTreechildren = document.createElement("treechildren");

    var devicesArr = getNewDevicesInfo();
    var devicesAccountsArr = getNewDeviceAccounts();

    for (i = 0; i < devicesArr.length; i++) {
        var newTreeitem = document.createElement("treeitem");
        newTreeitem.setAttribute("container", "true");
        newTreeitem.setAttribute("open", "true");
        newTreeitem.setAttribute("id", setDeviceID(devicesArr[i].dId));
        newTreeitem.setAttribute("statustext",setDeviceID(i));
        if (newTreeitem) {
            var newTreerow = document.createElement("treerow");
            var newTreecell = document.createElement("treecell");
            newTreecell.setAttribute("label", devicesArr[i].dName);
            newTreecell.setAttribute("src", "chrome://messenger/skin/icons/mobileIcon.png");
            newTreerow.appendChild(newTreecell);
            newTreeitem.appendChild(newTreerow);
        }
        var newTreechildrenAccount = document.createElement("treechildren");

        for (j = 0; j < devicesAccountsArr[i].length; j++) {
            var newTreeitemAccount = document.createElement("treeitem");
            newTreeitemAccount.setAttribute("container", "true");
            newTreeitemAccount.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId));
            newTreeitemAccount.setAttribute("statustext", setDeviceAccountID(i+"_"+j));
            if (newTreeitemAccount) {
                var newTreerowAccount = document.createElement("treerow");
                var newTreecellAccount = document.createElement("treecell");
                newTreecellAccount.setAttribute("src", "chrome://messenger/skin/icons/mailboxName.png");
                newTreecellAccount.setAttribute("label",  devicesAccountsArr[i][j].aName);
                newTreerowAccount.appendChild(newTreecellAccount);
                newTreeitemAccount.appendChild(newTreerowAccount);

                var accountChild = document.createElement("treechildren");
                var accountItem = document.createElement("treeitem");
                accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_6"));
                accountItem.setAttribute("statustext", setDeviceAccountID(i+"_"+j+"send"));
                var accountRow = document.createElement("treerow");
                var accountCell = document.createElement("treecell");
                accountCell.setAttribute("src","chrome://messenger/skin/icons/sentImg.png");
                accountCell.setAttribute("align","left");
                accountCell.setAttribute("label", "发件箱");
                accountRow.appendChild(accountCell);
                accountItem.appendChild(accountRow);
                accountChild.appendChild(accountItem);
                var accountItem = document.createElement("treeitem");
                accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_1"));
                accountItem.setAttribute("statustext", setDeviceAccountID(i+"_"+j+"recv"));
                var accountRow = document.createElement("treerow");
                var accountCell = document.createElement("treecell");
                accountCell.setAttribute("src","chrome://messenger/skin/icons/inboxImg.png");
                accountCell.setAttribute("align","left");
                //accountCell.setAttribute("style",'list-style-image: url("chrome://messenger/skin/icons/folder-pane.png");-moz-image-region: rect(64px 16px 80px 0px);');
                accountCell.setAttribute("label", "收件箱");
                accountRow.appendChild(accountCell);
                accountItem.appendChild(accountRow);
                accountChild.appendChild(accountItem);
                var accountItem = document.createElement("treeitem");
                accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_3"));
                accountItem.setAttribute("statustext", setDeviceAccountID(i+"_"+j+"draft"));
                var accountRow = document.createElement("treerow");
                var accountCell = document.createElement("treecell");
                accountCell.setAttribute("src","chrome://messenger/skin/icons/drafshImg.png");
                accountCell.setAttribute("align","left");
                accountCell.setAttribute("label", "草稿箱");
                accountRow.appendChild(accountCell);
                accountItem.appendChild(accountRow);
                accountChild.appendChild(accountItem);
                newTreeitemAccount.appendChild(accountChild);
            }
            newTreechildrenAccount.appendChild(newTreeitemAccount);
        }
        newTreeitem.appendChild(newTreechildrenAccount);

        newTreechildren.appendChild(newTreeitem);
    }
    Treeitem.appendChild(newTreechildren);
}

function setDeviceID(deviceName) {
    var tmp = "Device_";
    return tmp + deviceName;
}

function setDeviceAccountID(deviceAccountName) {
    var tmp = "Account_";
    return tmp + deviceAccountName;
}

function getOneDevicesInfo() {

    var comingDevices = new Array();
    if(window.arguments[1])
    {     
     while (window.arguments[1].initialized === false || window.arguments[1].dbStatus === false) {
        window.arguments[1].onLoad();
     }
     var statement = window.arguments[1].dbConnection.createStatement("\
              SELECT dName FROM td_device WHERE dStatus = 2 ORDER BY dId ASC");
    try {
        while (statement.executeStep()) {
            comingDevices.push(statement.row.dName);
        }
    }
    finally {
        statement.reset();
    }
    }else{
        
     while (dDeviceSqlite.initialized === false || dDeviceSqlite.dbStatus === false) {
        dDeviceSqlite.onLoad();
        
    }
      var statement = dDeviceSqlite.dbConnection.createStatement("\
              SELECT dName FROM td_device WHERE dStatus = 2 ORDER BY dId ASC");
    try {
        while (statement.executeStep()) {
            comingDevices.push(statement.row.dName);
        }
    }
    finally {
        statement.reset();
    }
 
    }/* 
    var statement = window.arguments[1].dbConnection.createStatement("\
              SELECT dName FROM td_device WHERE dStatus = 2 ORDER BY dId ASC");
    try {
        while (statement.executeStep()) {
            comingDevices.push(statement.row.dName);
        }
    }
    finally {
        statement.reset();
    }*/
    return comingDevices;
}

function getOneDeviceAccounts() {
    var devicesCount = new Array();
   
    if(window.arguments[1])
    {    
    while (window.arguments[1].initialized === false || window.arguments[1].dbStatus === false) {
        window.arguments[1].onLoad();
    }
    var statement = window.arguments[1].dbConnection.createStatement("\
                            SELECT dId FROM td_device WHERE dStatus = 2");
    try {
        while (statement.executeStep()) {
            devicesCount.push(statement.row.dId);
        }
    }
    finally {
        statement.reset();
    }
    }else{    
    while (dDeviceSqlite.initialized === false || dDeviceSqlite.dbStatus === false) {
        dDeviceSqlite.onLoad();
    }
    var statement=dDeviceSqlite.dbConnection.createStatement("\
                            SELECT dId FROM td_device WHERE dStatus = 2");
    try {
        while (statement.executeStep()) {
            devicesCount.push(statement.row.dId);
        }
    }
    finally {
        statement.reset();
    }    
        
    }
    var comingDeviceAccounts = new Array();
    for (i = 0; i < devicesCount.length; i++) {
        comingDeviceAccounts[i] = new Array();
    }
    if(window.arguments[1])
    {    
     while (window.arguments[1].initialized === false || window.arguments[1].dbStatus === false) {
        window.arguments[1].onLoad();
     }
    var statement = window.arguments[1].dbConnection.createStatement("\
     SELECT td_device.dId,td_account.aId,td_account.aName FROM td_account \
                    LEFT JOIN td_device ON td_device.dId = td_account.dId \
                   WHERE td_account.aRemoteStatus = 2 ORDER BY td_device.dId ASC");
    try {
        var index = 0, tmp = 0;
        while (statement.executeStep()) {
            if (0 === tmp) {
                tmp = statement.row.dId;
                comingDeviceAccounts[index].push(statement.row.aName);
            } else {
                if (tmp === statement.row.dId) {
                    comingDeviceAccounts[index].push(statement.row.aName);
                } else {
                    tmp = statement.row.dId;
                    index++;
                    comingDeviceAccounts[index].push(statement.row.aName);
                }
            }
        }
    }
    finally {
        statement.reset();
    }
  }else{
      
      while (dDeviceSqlite.initialized === false || dDeviceSqlite.dbStatus === false) {
        dDeviceSqlite.onLoad();
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
     SELECT td_device.dId,td_account.aId,td_account.aName FROM td_account \
                    LEFT JOIN td_device ON td_device.dId = td_account.dId \
                   WHERE td_account.aRemoteStatus = 2 ORDER BY td_device.dId ASC");
    try {
        var index = 0, tmp = 0;
        while (statement.executeStep()) {
            if (0 === tmp) {
                tmp = statement.row.dId;
                comingDeviceAccounts[index].push(statement.row.aName);
            } else {
                if (tmp === statement.row.dId) {
                    comingDeviceAccounts[index].push(statement.row.aName);
                } else {
                    tmp = statement.row.dId;
                    index++;
                    comingDeviceAccounts[index].push(statement.row.aName);
                }
            }
        }
    }
    finally {
        statement.reset();
    }
      
  }
    return comingDeviceAccounts;
}
/**/
function linkerrorjump()
{
    var hboxe1 = document.getElementById("messagepaneboxwrapper");
    //alert(hboxe1);
        hboxe1.setAttribute("align","center");
        var vboxe=document.createElement("vbox");
        vboxe.setAttribute("align","center");
        var validyid = document.getElementById("erweima");
        if (validyid.parentNode) {
        validyid.parentNode.removeChild(validyid);
        }
        var vcaption=document.createElement("caption");
        vcaption.setAttribute("label","注意：当前设备已有连接，请重启设备UPNP服务");
        vcaption.setAttribute("style","color:red");
        vcaption.setAttribute("align","center");
        var vdescription=document.createElement("description");
        vdescription.setAttribute("align","center");
        var vimage=document.createElement("image");
        vimage.setAttribute("src","chrome://messenger/skin/icons/linkerrorimage.gif");
        vdescription.appendChild(vimage);
        var vSpacer = document.createElement("space");
        vSpacer.setAttribute("style", "height:30px");
        
         var vSpacer1 = document.createElement("space");
        vSpacer1.setAttribute("style", "height:50px");
        
        vboxe.appendChild(vSpacer1);
        vboxe.appendChild(vcaption);
        vboxe.appendChild(vSpacer);
        vboxe.appendChild(vdescription);
        hboxe1.appendChild(vboxe);
}


function generationDEVQRCode(tabpanelID, vCode) {
    var curIndex = tabpanelID;
    var curTabpanel = document.getElementById(tabpanelID);
    var qrBox = document.createElement("box");
    qrBox.setAttribute("id", "device_tab_qrbox_" + curIndex);
    //alert("qrBox.id="+qrBox.id);
    var qrSpacer = document.createElement("space");
    qrSpacer.setAttribute("style", "height:10px");
    qrBox.appendChild(qrSpacer);
    var desLabel = document.createElementNS("http://www.w3.org/1999/xhtml", "div");
    desLabel.setAttribute("style", "height:30px;font-size:16px;margin-left:140px;");
    desLabel.innerHTML = "同一WI-FI环境中请使用终端设备扫描二维码或输入验证码进行连接：";
    qrBox.appendChild(desLabel);
    var radioBox = document.createElementNS("http://www.w3.org/1999/xhtml", "div");
    radioBox.setAttribute("style", "display:none;");

    var divInfos = [
        {id: "_1", value: "L", label: "7%"},
        {id: "_m", value: "M", label: "15%"},
        {id: "_q", value: "Q", label: "25%"},
        {id: "_h", value: "H", label: "30%"}
    ];
    for (var i = 0; i < divInfos.length; i++) {
        var inputName = document.createElementNS("http://www.w3.org/1999/xhtml", "input");
        inputName.setAttribute("id", "qr_capacity" + divInfos[i].id + "_" + curIndex);
        inputName.setAttribute("name", "qr_capacity");
        inputName.setAttribute("type", "radio");
        inputName.setAttribute("value", divInfos[i].value);
        radioBox.appendChild(inputName);
        var labelName = document.createElementNS("http://www.w3.org/1999/xhtml", "label");
        labelName.setAttribute("for", "qr_capacity" + divInfos[i].id + "_" + curIndex);
        labelName.innerHTML = divInfos[i].label;
        //alert(divInfos[i].label);
        radioBox.appendChild(labelName);
    }
    qrBox.appendChild(radioBox);
    var qrSpacer = document.createElement("space");
    qrSpacer.setAttribute("style", "height:10px");
    qrBox.appendChild(qrSpacer);
    var qrContainer = document.createElementNS("http://www.w3.org/1999/xhtml", "div");
    qrContainer.setAttribute("id", "qr_container_" + curIndex);
    qrContainer.setAttribute("style", "margin-left:280px;");
    qrBox.appendChild(qrContainer);
    var qrBr = document.createElementNS("http://www.w3.org/1999/xhtml", "br");
    qrBox.appendChild(qrBr);

    var qrDivLabel = document.createElementNS("http://www.w3.org/1999/xhtml", "div");

    var qrSpacer = document.createElement("space");
    qrSpacer.setAttribute("style", "width:155px;");
    qrDivLabel.appendChild(qrSpacer);
    var qrLabel = document.createElement("label");
    qrLabel.setAttribute("style", "font-size:18px;margin-left:160px;");
    qrLabel.setAttribute("value", "验证码：" + vCode);
    qrDivLabel.appendChild(qrLabel);
    //alert(qrLabel.getAttribute('value'));
    qrBox.appendChild(qrDivLabel);
    curTabpanel.appendChild(qrBox);

    var qr_coder = null;
    var container = document.getElementById(qrContainer.id);
    var jqContainer = $(container);
    qr_coder = new QRCoder(jqContainer);
    qr_coder.setMode(1);
    qr_coder.draw(vCode, "H", 'icon.png', function (data) {
    });
    //alert(qr_coder);
}

function devLinkSuccess() {

    var deviceTabs = document.getElementById("messagepaneboxwrapper");
    var validyid = document.getElementById("erweima");
    //alert(1111111111);
    if (validyid.parentNode) {
        validyid.parentNode.removeChild(validyid);
    }

    var statement = window.arguments[1].dbConnection.createStatement("\
                  UPDATE td_device SET dStatus = 2, dHandleStatus = 1 where dUDN = :myVal");
    statement.params.myVal = window.arguments[0].uuid;
    try {
        while (statement.executeStep()) {
            continue;
        }
    }
    finally {
        statement.reset();
    }


    saveDevAccountsInfoToDB(deviceTabs.id);
    createAccInfoPanel(deviceTabs.id); 
    /*连接成功后更新邮件树*/
    if(window.opener)
    {    
      var panelTree = window.opener.document.getElementById('folderPaneBox');
      //var treeSpr= window.opener.document.getElementById('hadTreeOrNewTree');
    }else{
      var panelTree = document.getElementById('folderPaneBox');
      //var treeSpr= document.getElementById('hadTreeOrNewTree');
    }
    if(panelTree)
    {
         var elem_child = panelTree.childNodes;
         for (var i = 0; i < elem_child.length; i++) {
        if ("showDevicesPanelTree" === elem_child[i].id) {
            elem_child[i].parentNode.removeChild(elem_child[i]);
        }   
    }
    createOneDeviceListToPanel();      
    } 
}

var gLocalAccountInfo = {
    realName: "email1",
    emailAddress: "邮箱地址",
    type: "pop3",
    recvHostname: "pop3.163.com",
    recvPort: "110",
    sendHostname: "smtp.163.com",
    sendPort: "25",
    userName: "邮箱名称",
    passWord: "邮箱密码",
    socketType: 3,
    auth: 3,
    source: 1
};

function AccountConfig()
{
    this.incoming = this.createNewIncoming();
    this.incomingAlternatives = [];
    this.outgoing = this.createNewOutgoing();
    this.outgoingAlternatives = [];
    this.identity =
            {
                realname: gLocalAccountInfo.realName,
                emailAddress: gLocalAccountInfo.emailAddress,
            };
    this.inputFields = [];
    this.domains = [];
}
;
AccountConfig.prototype =
        {
            incoming: null,
            outgoing: null,
            incomingAlternatives: null,
            outgoingAlternatives: null,
            id: null,
            source: gLocalAccountInfo.source,
            displayName: null,
            inputFields: null,
            domains: null,
            createNewIncoming: function ()
            {
                return {
                    type: gLocalAccountInfo.type,
                    hostname: gLocalAccountInfo.recvHostname,
                    port: gLocalAccountInfo.recvPort,
                    username: gLocalAccountInfo.userName,
                    password: gLocalAccountInfo.passWord,
                    socketType: gLocalAccountInfo.socketType,
                    badCert: false,
                    auth: gLocalAccountInfo.auth,
                    authAlternatives: null,
                    checkInterval: 10,
                    loginAtStartup: true,
                    useGlobalInbox: false,
                    leaveMessagesOnServer: true,
                    daysToLeaveMessagesOnServer: 14,
                    deleteByAgeFromServer: true,
                    deleteOnServerWhenLocalDelete: true,
                    downloadOnBiff: true,
                };
            },
            createNewOutgoing: function ()
            {
                return {
                    type: "smtp",
                    hostname: gLocalAccountInfo.sendHostname,
                    port: gLocalAccountInfo.sendPort,
                    username: gLocalAccountInfo.userName,
                    password: gLocalAccountInfo.passWord,
                    socketType: gLocalAccountInfo.socketType,
                    badCert: false,
                    auth: gLocalAccountInfo.auth,
                    authAlternatives: null,
                    addThisServer: true,
                    useGlobalPreferredServer: false,
                    existingServerKey: null,
                    existingServerLabel: null,
                };
            },
            copy: function ()
            {
                var result = new AccountConfig();
                for (var prop in this)
                    result[prop] = deepCopy(this[prop]);

                return result;
            },
            isComplete: function ()
            {
                return (!!this.incoming.hostname && !!this.incoming.port &&
                        !!this.incoming.socketType && !!this.incoming.auth &&
                        !!this.incoming.username &&
                        (!!this.outgoing.existingServerKey ||
                                (!!this.outgoing.hostname && !!this.outgoing.port &&
                                        !!this.outgoing.socketType && !!this.outgoing.auth &&
                                        !!this.outgoing.username)));
            },
        };

/*
 * function deleteSelection()
 {
 var list = document.getElementById('thelist');
 var count = list.selectedCount;
 while(count--){
 var item = list.selectedItems[0];
 list.removeItemAt(list.getIndexOfItem(item));
 }
 }
 */
//function test()
//{
//    
//    alert("点击");
//    
//}